// exploreScript.js

let currentPage = 1;
let pageSize = 12;
let totalPages = 0;
let currentScripts = [];

// DOM加载完成后初始化
$(document).ready(function() {
    initEventListeners();
    loadScripts();
});

// 初始化事件监听器
function initEventListeners() {
    // 搜索按钮
    $('#searchBtn').click(function() {
        currentPage = 1;
        loadScripts();
    });

    // 分页控制
    $('#prevPage').click(function() {
        if (currentPage > 1) {
            currentPage--;
            loadScripts();
        }
    });

    $('#nextPage').click(function() {
        if (currentPage < totalPages) {
            currentPage++;
            loadScripts();
        }
    });

    // 页面大小改变
    $('#pageSize').change(function() {
        pageSize = parseInt($(this).val());
        currentPage = 1;
        loadScripts();
    });

    // 回车键搜索
    $('#titleFilter, #themeFilter, #userIdFilter').keypress(function(e) {
        if (e.which === 13) {
            currentPage = 1;
            loadScripts();
        }
    });

    // 发布状态筛选
    $('#sharedFilter').change(function() {
        currentPage = 1;
        loadScripts();
    });
}

// 加载剧本数据
function loadScripts() {
    showLoading();

    const params = {
        page: currentPage,
        pageSize: pageSize,
        title: $('#titleFilter').val().trim(),
        theme: $('#themeFilter').val().trim(),
        userId: $('#userIdFilter').val().trim(),
        isShared: $('#sharedFilter').val()
    };

    // 清理空参数
    Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
            delete params[key];
        }
    });

    $.ajax({
        url: '/exploreScript/list',
        type: 'GET',
        data: params,
        success: function(response) {
            hideLoading();
            console.log(response)
            if (response.code ==200) {

                currentScripts = response.data.records || [];
                totalPages = response.data.pages || 1;
                renderScriptCards(response.data.rows);
                renderPagination();
            } else {
                showErrorAlert(response.message || '加载数据失败');
            }
        },
        error: function(xhr, status, error) {
            hideLoading();
            showErrorAlert('网络错误: ' + (xhr.responseJSON?.message || error));
        }
    });
}

// 渲染剧本卡片
function renderScriptCards(scripts) {
    console.log(scripts)
    const container = $('#cardsContainer');

    if (!scripts || scripts.length === 0) {
        container.html(`
            <div class="empty-state">
                <i class="bi bi-journal-x"></i>
                <h3>暂无剧本数据</h3>
                <p>没有找到符合条件的探店剧本</p>
            </div>
        `);
        return;
    }

    const cardsHtml = scripts.map(script => `
        <div class="script-card" data-id="${script.id}">
            <div class="card-header">
                <div class="card-id">ID: ${script.id}</div>
                <span class="card-status ${script.isShared ? 'status-shared' : 'status-private'}">
                    ${script.isShared ? '已发布' : '未发布'}
                </span>
            </div>
            
            <div class="card-body">
                <div class="script-info">
                    ${script.coverImageUrl ? `
                        <img src="${script.coverImageUrl}" alt="${script.title}" class="script-cover" 
                             onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                        <div class="script-cover-placeholder" style="display: none;">
                            <i class="bi bi-journal-text"></i>
                        </div>
                    ` : `
                        <div class="script-cover-placeholder">
                            <i class="bi bi-journal-text"></i>
                        </div>
                    `}
                    
                    <div class="script-details">
                        <h3>${script.title || '无标题'}</h3>
                        <p><i class="bi bi-tags"></i> ${script.theme || '无标签'}</p>
                        <p><i class="bi bi-person"></i> ${script.username ? '剧本创建者: ' + script.username : '官方剧本'}</p>
                    </div>
                </div>
                
                <div class="card-content">
                    <div class="content-text ${script.description && script.description.length > 100 ? 'expandable' : ''}">
                        ${script.description || '暂无描述'}
                    </div>
                </div>
                
                <div class="card-stats">
                    <div class="stat-item">
                        <i class="bi bi-eye stat-icon"></i>
                        <div>
                            <div class="stat-value">${script.viewCount || 0}</div>
                            <div class="stat-label">查看</div>
                        </div>
                    </div>
                    <div class="stat-item">
                        <i class="bi bi-play-circle stat-icon"></i>
                        <div>
                            <div class="stat-value">${script.usedCount || 0}</div>
                            <div class="stat-label">使用</div>
                        </div>
                    </div>
                    <div class="stat-item">
                        <i class="bi bi-heart stat-icon"></i>
                        <div>
                            <div class="stat-value">${script.likeCount || 0}</div>
                            <div class="stat-label">点赞</div>
                        </div>
                    </div>
                    <div class="stat-item">
                        <i class="bi bi-star stat-icon"></i>
                        <div>
                            <div class="stat-value">${script.favoriteCount || 0}</div>
                            <div class="stat-label">收藏</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="card-footer">
                <div class="card-date">
                    <i class="bi bi-clock"></i>
                    ${formatDate(script.createdAt)}
                </div>
                <div class="card-actions">
                    <button class="btn-action btn-view" onclick="viewScript(${script.id})">
                        <i class="bi bi-eye"></i> 查看
                    </button>
                    <button class="btn-action btn-delete" onclick="deleteScript(${script.id})">
                        <i class="bi bi-trash"></i> 删除
                    </button>
                </div>
            </div>
        </div>
    `).join('');

    container.html(cardsHtml);
}

// 查看剧本详情
function viewScript(scriptId) {
    const script = currentScripts.find(s => s.id === scriptId);
    console.log(scriptId)
    if (scriptId) {
        showScriptDetailModal(scriptId);
    }
}

// 编辑剧本
function editScript(scriptId) {
    // 这里可以跳转到编辑页面或打开编辑模态框
    showSuccessAlert('编辑功能开发中...');
    // window.location.href = `/explore-scripts/edit/${scriptId}`;
}

// 删除剧本
function deleteScript(scriptId) {
    if (!confirm('确定要删除这个剧本吗？此操作不可恢复！')) {
        return;
    }

    showLoading();

    $.ajax({
        url: `/api/exploration-scripts/${scriptId}`,
        type: 'DELETE',
        headers: {
            'X-CSRF-TOKEN': getCsrfToken()
        },
        success: function(response) {
            hideLoading();
            if (response.success) {
                showSuccessAlert('剧本删除成功');
                loadScripts(); // 重新加载数据
            } else {
                showErrorAlert(response.message || '删除失败');
            }
        },
        error: function(xhr, status, error) {
            hideLoading();
            showErrorAlert('删除失败: ' + (xhr.responseJSON?.message || error));
        }
    });
}

// 渲染分页控件
function renderPagination() {
    const pageNumbers = $('#pageNumbers');
    pageNumbers.empty();

    // 显示页码范围
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);

    // 上一页按钮状态
    $('#prevPage').toggleClass('disabled', currentPage === 1);

    // 生成页码按钮
    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = $(`<button class="page-btn ${i === currentPage ? 'active' : ''}">${i}</button>`);
        pageBtn.click(() => {
            if (i !== currentPage) {
                currentPage = i;
                loadScripts();
            }
        });
        pageNumbers.append(pageBtn);
    }

    // 下一页按钮状态
    $('#nextPage').toggleClass('disabled', currentPage === totalPages);

    // 更新页面信息
    $('.page-info').remove();
    const pageInfo = $(`<div class="page-info" style="margin-left: 15px; font-size: 14px; color: #666;">
        第 ${currentPage} 页，共 ${totalPages} 页
    </div>`);
    $('.pagination').append(pageInfo);
}

// 显示加载动画
function showLoading() {
    $('#cardsContainer').html(`
        <div style="grid-column: 1 / -1; text-align: center; padding: 60px;">
            <div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-3 text-muted">加载中...</p>
        </div>
    `);
}

// 隐藏加载动画
function hideLoading() {
    // 加载状态会在renderScriptCards中清除
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return 'N/A';
    try {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });
    } catch (e) {
        return '无效日期';
    }
}

// 获取CSRF Token（如果使用Spring Security等）
function getCsrfToken() {
    return $('meta[name="_csrf"]').attr('content') ||
        $('input[name="_csrf"]').val() ||
        $.cookie('XSRF-TOKEN');
}

// 添加剧本（如果需要）
function addScript() {
    // 这里可以实现添加剧本的功能
    showSuccessAlert('添加功能开发中...');
    // window.location.href = '/explore-scripts/add';
}

// 批量操作示例
function batchDeleteScripts() {
    const selectedScripts = currentScripts.filter(script =>
        $(`#script-${script.id}`).is(':checked')
    );

    if (selectedScripts.length === 0) {
        showErrorAlert('请先选择要删除的剧本');
        return;
    }

    if (!confirm(`确定要删除选中的 ${selectedScripts.length} 个剧本吗？`)) {
        return;
    }

    const scriptIds = selectedScripts.map(script => script.id);

    showLoading();

    $.ajax({
        url: '/api/exploration-scripts/batch-delete',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ ids: scriptIds }),
        headers: {
            'X-CSRF-TOKEN': getCsrfToken()
        },
        success: function(response) {
            hideLoading();
            if (response.success) {
                showSuccessAlert(`成功删除 ${selectedScripts.length} 个剧本`);
                loadScripts();
            } else {
                showErrorAlert(response.message || '批量删除失败');
            }
        },
        error: function(xhr, status, error) {
            hideLoading();
            showErrorAlert('批量删除失败: ' + (xhr.responseJSON?.message || error));
        }
    });
}

// 导出数据
function exportScripts() {
    const params = {
        title: $('#titleFilter').val().trim(),
        theme: $('#themeFilter').val().trim(),
        userId: $('#userIdFilter').val().trim(),
        isShared: $('#sharedFilter').val()
    };

    const queryString = new URLSearchParams(params).toString();
    window.open(`/api/exploration-scripts/export?${queryString}`, '_blank');
}

// 错误处理
function handleApiError(xhr) {
    let errorMessage = '请求失败';

    if (xhr.status === 401) {
        errorMessage = '未授权，请重新登录';
        // 可以跳转到登录页面
        // window.location.href = '/login';
    } else if (xhr.status === 403) {
        errorMessage = '权限不足';
    } else if (xhr.status === 404) {
        errorMessage = '资源未找到';
    } else if (xhr.status === 500) {
        errorMessage = '服务器内部错误';
    }

    if (xhr.responseJSON && xhr.responseJSON.message) {
        errorMessage += ': ' + xhr.responseJSON.message;
    }

    showErrorAlert(errorMessage);
}

// 添加搜索框的实时搜索（可选）
function initRealTimeSearch() {
    let searchTimer;
    $('#titleFilter, #themeFilter').on('input', function() {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(() => {
            currentPage = 1;
            loadScripts();
        }, 500);
    });
}

// 初始化实时搜索（如果需要）
// initRealTimeSearch();

// 显示成功消息
// 显示成功提示
function showSuccessAlert(message, duration = 5000) {
    const alert = document.getElementById('success-alert');
    const messageElement = document.getElementById('success-message');

    // 设置消息内容
    messageElement.textContent = message || '操作已成功完成';

    // 显示提示框
    alert.classList.add('show');

    // 添加进度条
    addProgressBar(alert, duration);

    // 自动隐藏
    setTimeout(() => {
        hideSuccessAlert();
    }, duration);
}

// 显示错误提示
function showErrorAlert(message, duration = 5000) {
    const alert = document.getElementById('error-alert');
    const messageElement = document.getElementById('error-message');

    // 设置消息内容
    messageElement.textContent = message || '操作过程中出现错误';

    // 显示提示框
    alert.classList.add('show');

    // 添加进度条
    addProgressBar(alert, duration);

    // 自动隐藏
    setTimeout(() => {
        hideErrorAlert();
    }, duration);
}

// 隐藏成功提示
function hideSuccessAlert() {
    const alert = document.getElementById('success-alert');
    alert.classList.remove('show');
    removeProgressBar(alert);
}

// 隐藏错误提示
function hideErrorAlert() {
    const alert = document.getElementById('error-alert');
    alert.classList.remove('show');
    removeProgressBar(alert);
}

// 添加进度条
function addProgressBar(alert, duration) {
    removeProgressBar(alert);

    const progressBar = document.createElement('div');
    progressBar.className = 'alert-progress';
    progressBar.style.animationDuration = duration + 'ms';

    alert.querySelector('.alert-content').appendChild(progressBar);
}

// 移除进度条
function removeProgressBar(alert) {
    const existingProgress = alert.querySelector('.alert-progress');
    if (existingProgress) {
        existingProgress.remove();
    }
}

// 点击提示框外部关闭
document.addEventListener('click', function(event) {
    const successAlert = document.getElementById('success-alert');
    const errorAlert = document.getElementById('error-alert');

    if (successAlert.classList.contains('show') &&
        !event.target.closest('#success-alert')) {
        hideSuccessAlert();
    }

    if (errorAlert.classList.contains('show') &&
        !event.target.closest('#error-alert')) {
        hideErrorAlert();
    }
});
// 显示剧本详情模态框
function showScriptDetailModal(scriptId) {
    let script;
    console.log(scriptId);
    $.ajax({
        url: "/exploreScript/getById",
        type: 'GET',
        data: { id: scriptId },
        async: false,
        success: function(response) {
            script = response.data;
        },
    });

    const detailHtml = `
        <div class="detail-section">
            <h4><i class="bi bi-info-circle"></i>基本信息</h4>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">剧本ID</span>
                    <div class="detail-value">${script.id}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">发布状态</span>
                    <div class="detail-value">
                        <span class="card-status ${script.isShared ? 'status-shared' : 'status-private'}">
                            ${script.isShared ? '已发布' : '未发布'}
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <div class="detail-section">
            <h4><i class="bi bi-journal-text"></i>剧本内容</h4>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">剧本标题</span>
                    <div class="detail-value">${script.title || '无标题'}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">主题标签</span>
                    <div class="detail-value">${script.theme || '无标签'}</div>
                </div>
            </div>
            <div class="detail-item" style="margin-top: 10px;">
                <span class="detail-label">剧本描述</span>
                <div class="detail-content">${script.description || '无描述'}</div>
            </div>
        </div>

        <div class="detail-section">
            <h4><i class="bi bi-shop"></i>店铺信息</h4>
            <div class="detail-item">
                <span class="detail-label">店铺顺序</span>
                <div class="detail-content">${formatShopOrder(script.shopOrder)}</div>
            </div>
        </div>

        <div class="detail-section">
            <h4><i class="bi bi-graph-up"></i>统计数据</h4>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">查看次数</span>
                    <div class="detail-value">${script.viewCount || 0}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">使用次数</span>
                    <div class="detail-value">${script.usedCount || 0}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">点赞数</span>
                    <div class="detail-value">${script.likeCount || 0}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">收藏数</span>
                    <div class="detail-value">${script.favoriteCount || 0}</div>
                </div>
            </div>
        </div>

        <div class="detail-section">
            <h4><i class="bi bi-clock"></i>时间信息</h4>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">创建时间</span>
                    <div class="detail-value">${formatDate(script.createdAt)}</div>
                </div>
                ${script.updatedAt && script.updatedAt !== script.createdAt ? `
                <div class="detail-item">
                    <span class="detail-label">更新时间</span>
                    <div class="detail-value">${formatDate(script.updatedAt)}</div>
                </div>
                ` : ''}
            </div>
        </div>

        ${script.user_id ? `
        <div class="detail-section">
            <h4><i class="bi bi-person"></i>用户信息</h4>
            <div class="detail-item">
                <span class="detail-label">用户ID</span>
                <div class="detail-value">${script.user_id}</div>
            </div>
        </div>
        ` : ''}

        ${script.cover_image_url ? `
        <div class="detail-section">
            <h4><i class="bi bi-image"></i>封面图片</h4>
            <div class="detail-item">
                <img src="${script.cover_image_url}" alt="封面图" style="max-width: 100%; border-radius: 8px;">
            </div>
        </div>
        ` : ''}
    `;

    $('#modalBody').html(detailHtml);
    $('#detailModal').show();
}
// 显示编辑模态框
function showEditScriptModal(script) {
    // 填充表单数据
    $('#scriptId').val(script.id);
    $('#title').val(script.title || '');
    $('#theme').val(script.theme || '');
    $('#description').val(script.description || '');
    $('#coverImageUrl').val(script.cover_image_url || '');
    $('#shopOrder').val(JSON.stringify(script.shop_order || []));
    $('#routePolyline').val(script.route_polyline || '');
    $('#userId').val(script.user_id || '');
    $('#isShared').val(script.is_shared ? '1' : '0');

    $('#modalTitle').text('编辑剧本');
    $('#scriptModal').show();
}

// 保存剧本（添加/编辑）
function saveScript(formData) {
    showLoading();

    const url = formData.id ? `/api/exploration-scripts/${formData.id}` : '/api/exploration-scripts';
    const method = formData.id ? 'PUT' : 'POST';

    $.ajax({
        url: url,
        type: method,
        contentType: 'application/json',
        data: JSON.stringify(formData),
        headers: {
            'X-CSRF-TOKEN': getCsrfToken()
        },
        success: function(response) {
            hideLoading();
            if (response.success) {
                showSuccessAlert(formData.id ? '剧本更新成功' : '剧本添加成功');
                $('#scriptModal').hide();
                loadScripts();
            } else {
                showErrorAlert(response.message || '保存失败');
            }
        },
        error: function(xhr, status, error) {
            hideLoading();
            showErrorAlert('保存失败: ' + (xhr.responseJSON?.message || error));
        }
    });
}
// 删除剧本
function deleteScript(scriptId) {
    if (!confirm('确定要删除这个剧本吗？此操作不可恢复！')) {
        return;
    }

    showLoading();

    $.ajax({
        url: `/api/exploration-scripts/${scriptId}`,
        type: 'DELETE',
        headers: {
            'X-CSRF-TOKEN': getCsrfToken()
        },
        success: function(response) {
            hideLoading();
            if (response.success) {
                showSuccessAlert('剧本删除成功');
                loadScripts();
            } else {
                showErrorAlert(response.message || '删除失败');
            }
        },
        error: function(xhr, status, error) {
            hideLoading();
            showErrorAlert('删除失败: ' + (xhr.responseJSON?.message || error));
        }
    });
}

// 批量删除
function batchDeleteScripts(scriptIds) {
    if (!scriptIds || scriptIds.length === 0) {
        showErrorAlert('请先选择要删除的剧本');
        return;
    }

    if (!confirm(`确定要删除选中的 ${scriptIds.length} 个剧本吗？`)) {
        return;
    }

    showLoading();

    $.ajax({
        url: '/api/exploration-scripts/batch-delete',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ ids: scriptIds }),
        headers: {
            'X-CSRF-TOKEN': getCsrfToken()
        },
        success: function(response) {
            hideLoading();
            if (response.success) {
                showSuccessAlert(`成功删除 ${scriptIds.length} 个剧本`);
                loadScripts();
            } else {
                showErrorAlert(response.message || '批量删除失败');
            }
        },
        error: function(xhr, status, error) {
            hideLoading();
            showErrorAlert('批量删除失败: ' + (xhr.responseJSON?.message || error));
        }
    });
}
// 更新剧本状态（发布/取消发布）
function updateScriptStatus(scriptId, isShared) {
    showLoading();

    $.ajax({
        url: `/api/exploration-scripts/${scriptId}/status`,
        type: 'PATCH',
        contentType: 'application/json',
        data: JSON.stringify({ is_shared: isShared }),
        headers: {
            'X-CSRF-TOKEN': getCsrfToken()
        },
        success: function(response) {
            hideLoading();
            if (response.success) {
                showSuccessAlert(isShared ? '剧本已发布' : '剧本已取消发布');
                loadScripts();
            } else {
                showErrorAlert(response.message || '状态更新失败');
            }
        }

    });
}

// 快速发布/取消发布
function toggleScriptStatus(scriptId, currentStatus) {
    const newStatus = !currentStatus;
    updateScriptStatus(scriptId, newStatus);
}
// 格式化店铺顺序
function formatShopOrder(shopOrder) {
    if (!shopOrder) return '无店铺顺序';

    try {
        const order = typeof shopOrder === 'string' ? JSON.parse(shopOrder) : shopOrder;

        if (!Array.isArray(order) || order.length === 0) {
            return '无店铺顺序';
        }

        // 如果是店铺ID数组，需要获取店铺详情
        if (typeof order[0] === 'number' || typeof order[0] === 'string') {
            return formatShopIds(order);
        }

        // 如果是包含店铺信息的对象数组
        if (Array.isArray(order) && order[0] && typeof order[0] === 'object') {
            return formatShopObjects(order);
        }

        return '格式错误';
    } catch (e) {
        return '格式错误';
    }
}

// 处理店铺ID数组
function formatShopIds(shopIds) {
    loadShopDetails(shopIds)
    // return `
    //     <div class="shop-order-list">
    //         ${shopIds.map((shopId, index) => `
    //             <div class="shop-order-item" data-shop-id="${shopId}">
    //                 <div class="shop-order-number">${index + 1}</div>
    //                 <div class="shop-order-content">
    //                     <div class="shop-name">店铺ID: ${shopId}</div>
    //                     <div class="shop-loading">加载中...</div>
    //                 </div>
    //             </div>
    //         `).join('')}
    //     </div>
    // `;
}

// 处理包含店铺信息的对象数组
function formatShopObjects(shops) {
    return `
        <div class="shop-order-list">
            ${shops.map((shop, index) => `
                <div class="shop-order-item">
                    <div class="shop-order-number">${index + 1}</div>
                    <div class="shop-order-content">
                        ${shop.image ? `
                            <img src="${shop.image}" alt="${shop.name}" class="shop-image" 
                                 onerror="this.style.display='none'">
                        ` : ''}
                        <div class="shop-info">
                            <div class="shop-name">${shop.name || '未知店铺'}</div>
                            ${shop.address ? `<div class="shop-address">${shop.address}</div>` : ''}
                            ${shop.description ? `<div class="shop-description">${shop.description}</div>` : ''}
                        </div>
                    </div>
                </div>
            `).join('')}
        </div>
    `;
}

// 加载店铺详情
function loadShopDetails(shopIds) {
    if (!shopIds || shopIds.length === 0) return;

    // 批量获取店铺信息
    $.ajax({
        url: 'exploreScript/getByIds',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(shopIds),
        success: function(response) {
            if (response.code == 200) {
                console.log(response.data)
                updateShopOrderDisplay(shopIds, response.data);
            }
        },
        error: function(xhr) {
            // 如果批量获取失败，回退到显示ID
            shopIds.forEach(shopId => {
                $(`.shop-order-item[data-shop-id="${shopId}"] .shop-loading`).text(`店铺ID: ${shopId}`);
            });
        }
    });
}

// 更新店铺显示
function updateShopOrderDisplay(shopIds, shopsData) {
    const thirdDetailSection = $('.detail-section:nth-child(3)');

// 清空第三个detail-section的内容，准备重新渲染
    thirdDetailSection.html(`
    <h4><i class="bi bi-shop"></i>探店路线</h4>
    <div class="shop-order-list" id="shopOrderList">
        <!-- 店铺列表将在这里动态生成 -->
    </div>
`);

    const shopOrderList = $('#shopOrderList');

    shopIds.forEach((shopId, index) => {
        const shop = shopsData.find(s => s.id == shopId);
        console.log(shop);

        if (shop) {
            // 为每个店铺创建一个detail-item
            const shopItemHtml = `
    <div class="detail-item shop-order-item" data-shop-id="${shopId}">
        <div class="shop-header">
            <div class="shop-order-number">
                <i class="bi bi-geo-alt"></i>
                <span>第${index + 1}站</span>
            </div>
        </div>
        <div class="detail-content shop-detail-content">
            <div class="shop-card">
                ${shop.avatarUrl ? `
                        <img src="${shop.avatarUrl}" alt="${shop.name}" class="shop-image" 
                             onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                ` : `
                    <div class="shop-image-placeholder">
                        <i class="bi bi-shop"></i>
                    </div>
                `}
                    <h4 class="shop-name">${shop.name || '未知店铺'}</h4>
                    ${shop.description ? `
                        <div class="shop-description">
                            <i class="bi bi-chat-text"></i>
                            ${shop.description}
                        </div>
                    ` : ''}
            </div>
        </div>
    </div>
`;
            shopOrderList.append(shopItemHtml);
        } else {
            // 店铺不存在的情况
            const shopItemHtml = `
            <div class="detail-item shop-order-item" data-shop-id="${shopId}">
                <span class="detail-label">第${index + 1}站</span>
                <div class="detail-content">
                    <div class="shop-loading">店铺不存在 (ID: ${shopId})</div>
                </div>
            </div>
        `;
            shopOrderList.append(shopItemHtml);
        }
    });
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return 'N/A';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 获取CSRF Token
function getCsrfToken() {
    return $('meta[name="_csrf"]').attr('content') ||
        $('input[name="_csrf"]').val() ||
        $.cookie('XSRF-TOKEN');
}
$("#closeModal").on("click",function (res){
    $("#detailModal").hide();
})